//boolean status for learning
var learning = false;

//lesson content
var lines = new Array();
var dict = new Object();

//current line number of lesson
var cur_line = 0;
var cur_row = 0;
var cur_ans;

//user keystroke stack
var key_stack = new Array();

var score = 0;

var key_smap = new Object();
var key_ymap = new Object();
key_ymap['q'] = 'iu';
key_ymap['w'] = 'ei';
key_ymap['r'] = 'uan';
key_ymap['t'] = 'ue';
key_ymap['y'] = 'un';
key_smap['u'] = 'sh';
key_smap['i'] = 'ch';
key_ymap['o'] = 'o/uo';
key_ymap['p'] = 'ie';
key_ymap['s'] = 'ong<br/>iong';
key_ymap['d'] = 'ai';
key_ymap['f'] = 'en';
key_ymap['g'] = 'eng';
key_ymap['h'] = 'ang';
key_ymap['j'] = 'an';
key_ymap['k'] = 'uai<br/>ing';
key_ymap['l'] = 'iang<br/>uang';
key_ymap['z'] = 'ou';
key_ymap['x'] = 'ia';
key_ymap['c'] = 'ao';
key_smap['v'] = 'zh';
key_ymap['v'] = 'v/ui';
key_ymap['b'] = 'in';
key_ymap['n'] = 'iao';
key_ymap['m'] = 'ian';

var show_next_line = function(){
	if (!learning) return;
	$('#text').fadeOut("fast", function(){
		$('#text').html(lines[cur_line]+"<br/>");
		$('#text').fadeIn("fast");
	});
    prepare_new_char();
}

var prepare_new_char = function() {
    cur_ans = dict[lines[cur_line].charAt(cur_row)];
    for (var i = 0; i < cur_ans.length; i++) if (cur_ans[i].length == 2) {
        var shengmu = cur_ans[i][0];
        var skey = key_smap[shengmu];
        if (skey != undefined) {
            $('#key-'+shengmu).html(shengmu.toUpperCase() + '<span class="shengmu">'+key_smap[shengmu]+'</span>');
        }
        var yunmu = cur_ans[i][1];
        var ykey = key_ymap[yunmu];
        if (ykey != undefined) {
            $('#key-'+yunmu).html(yunmu.toUpperCase() + '<span class="yunmu">'+key_ymap[yunmu]+'</span>');
        }
    }
    console.log('cur_ans: '+cur_ans);
}

var clear_prev_char = function() {
    cur_ans = dict[lines[cur_line].charAt(cur_row)];
    for (var i = 0; i < cur_ans.length; i++) if (cur_ans[i].length == 2) {
        var shengmu = cur_ans[i][0];
        $('#key-'+shengmu).html(shengmu.toUpperCase());
        var yunmu = cur_ans[i][1];
        $('#key-'+yunmu).html(yunmu.toUpperCase());
    }
}

//accept the input for the current position.
var accept_char = function(pos){
    score += 1;
    clear_prev_char();
	console.log('accepted char');
    $('#text').append(lines[cur_line].charAt(cur_row));
    key_stack.length = 0;
    cur_row++;
    if (cur_row >= lines[cur_line].length) {
        cur_line++;
        cur_row = 0;
        if (cur_line >= lines.length){
		    learning = false;
    		alert("Conguatulations! You have finish this course!!");
            finish_course();
        } else {
            show_next_line();
        }
    }
    prepare_new_char();
}

var finish_course = function() {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState != 4) return;
        $(location).attr('href', 'dashboard.php');
    }
    xhr.open('POST', 'score.php');
    xhr.send(score);
}

var handle_keypress = function(key_pressed) {
		$("div button[data-key-value=\""+String.fromCharCode(key_pressed)+"\"]").trigger("focus");
        key_stack.push(key_pressed);
        console.log(key_stack);
        if (key_stack.length >= cur_ans[0].length) {
            var current = '';
            for (var i = key_stack.length - cur_ans[0].length; i < key_stack.length; i++) {
                    current += String.fromCharCode(key_stack[i]);
            }
            for (var i = 0; i < cur_ans.length; i++) {
                if (cur_ans[i] == current) {
                    accept_char();
                }
            }
        }
}
$(document).keydown(function(e) {
    if (e.keyCode === 8) {
        return false;
    }
});
$(document).ready(function(){
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState != 4) return;
        var result = xhr.responseText;
        var resultArray = result.split('\n');
        var ln = 0;
        // lines
        for (; ln < resultArray.length && resultArray[ln]; ln++) {
            lines.push(resultArray[ln]); 
        }
        // answer map
        for (ln++; ln < resultArray.length && resultArray[ln]; ln++) {
           var key_char_pair = resultArray[ln].split(' ');
           if (dict[key_char_pair[0]] == undefined) {
                dict[key_char_pair[0]] = new Array();
           }
           dict[key_char_pair[0]].push(key_char_pair[1]);
        } 
        learning = true;
        
        show_next_line();
    	$("body").keydown(function(e){
		if (e.which == 27){
			$(location).attr('href', 'dashboard.php');
		}	
	});
	    $("body").keypress(function(e){
    		if (!learning) return;
		    var e = e || event;
	    	var key_pressed = e.keyCode || e.which;
    		console.log("pressed key number " + key_pressed);
	        handle_keypress(key_pressed);
        });

        $("div button").click(function(){
            if (!learning) return;
            var input=$(this).attr("data-key-value");
            var key_pressed = input.charCodeAt();
            console.log("clicked key number " + key_pressed);
            handle_keypress(key_pressed);
        });
    }; 
    xhr.open('POST', 'load_exercise_with_ans.php', true);
    xhr.send(exercise_id); // TODO: get exercise id
});
